import React, { Component } from 'react';
import { connect } from 'dva';
import { message, Modal, Button, Steps, Icon, Menu, Dropdown, Progress, Tooltip } from 'antd';
import styles from '../Users.css';
import Factory from '../../factory';
import dataEditCreate from '../../addons/DataEdit'
import dataTableCreate from '../../addons/DataTable'
import dataImportCreate from '../../addons/DataImport'
import * as datetime from '../../../utils/datetime'
import * as compDiviService from '../../../services/AccountDivi';
const daoName = "LCYX";
const ButtonGroup = Button.Group;    
const renderStep = (data) => {
    const { progress, status } = data
    const percent = Math.round(progress)
    return <Progress percent={percent} size="small" status={status === "" ? "normal" : status} />
};

const columns = [     
  { title: "当前进度", key: "StepName", render: data => renderStep(data), width: 160, dispaly: true },
  { title: '流程名称', width: 150, sorter: true, dataIndex: 'LCMC', key: 'LCMC', dispaly: true, filter: true,  },
  { title: '申请人', width: 150, sorter: true, dataIndex: 'SQR', key: 'SQR', dispaly: true, canEdit: true, filter: true, },
  { title: '当前在办', width: 150, sorter: true, dataIndex: 'DQZB', key: 'DQZB', dispaly: true, canEdit: true, filter: true, },
  { title: '当前状态', width: 150, sorter: true, dataIndex: 'DQZT', key: 'DQZT', dispaly: true, canEdit: true, filter: true, },
  { title: '申请时间', width: 150, sorter: true, dataIndex: 'SQSJ', key: 'SQSJ', dispaly: true, canEdit: true, filter: true, },
  { title: '认定/变更日期', width: 150, sorter: true, dataIndex: 'RDBGRQ', key: 'RDBGRQ', dispaly: true, canEdit: true, filter: true, },
//   { title: '申请时间', width: 150, sorter: true, dataIndex: 'SQSJ', key: 'SQSJ', dispaly: true, canEdit: true, filter: true, },
  { title: '完结时间', width: 150, sorter: true, dataIndex: 'WJSJ', key: 'WJSJ', dispaly: true, canEdit: true, filter: true, },

];
let controls = [
  { name: 'LCMC', required: true, type: 'text', dataType: "string",  label: '流程名称', grid: 12 / 24 },
  { name: "RDBGRQ", label: "认定变更日期", type: 'text', grid: 12 / 24},
  { name: "SQSJ", label: "申请时间", type: 'text', grid: 12 / 24 },
  { name: 'SQR', required: true, type: 'text',dataType: "string",   label: '申请人', grid: 12 / 24 },
  { name: 'DQZB', required: true, type: 'text', dataType: "string",  label: '当前在办', grid: 12 / 24 },
  { name: 'DQZT', required: true, type: 'text',dataType: "string",   label: '当前状态', grid: 12 / 24 },
  { name: "WJSJ", label: "完结时间", type: 'text', grid: 12 / 24 },

];

const EditFrom = dataEditCreate(daoName);
const DataTable = dataTableCreate(daoName);
const DataImport = dataImportCreate(daoName);
const DataTable2 = dataTableCreate("CompAccoFlow");
const Step = Steps.Step

class LCYXCollect extends Component {
    constructor(props) {
        super(props);
        this.state = {
            dataChange: false,
            range: "doing",
            stepTitle: "",
            canEdit: false,
            isClick: false
        };
    }
    componentDidMount() {
        this.loadData()
        this.loadOptionData()
    }
    loadData() {
        const seeks = [{
            WhereItems: [{
                FieldName: "#flowType",
                Operator: "=",
                FieldValues: '' + this.state.range,
            }],
            RelationSign: "AND"
        }];
        this.props.dispatch({
            type: `${daoName}/fetch`,
            payload: { daoName, page: 1, pageSize: 20, seeks }
        });
    }
    searchData() {
        const form = this.refs.searchForm.getForm()
        form.validateFields((err, values) => {
            const acno = values.ACNO

            if (!err) {
                compDiviService.GetCompIsDivi({ acno }
                ).then(function (data) {
                    if (data === 'N') {
                        message.error("客户为新客户，请按照新客户申请！")
                        return
                    } else if(data==='err'){
                        message.error("该客户在系统中不存在！")
                        return 
                    }else {
                        const seeks = [{
                            WhereItems: [{
                                FieldName: "ACNO",
                                Operator: "=",
                                FieldValues: acno,
                            }, {
                                FieldName: "ISDIVI",
                                Operator: "=",
                                FieldValues: '1',
                            }],
                            RelationSign: "AND"
                        }];

                        this.props.dispatch({
                            type: `CompAccoFlow/fetch`,
                            payload: { daoName: "CompAccoFlow", page: 1, pageSize: 10, seeks, acno }
                        });
                    }
                }.bind(this)).catch(function (ex) {
                    console.log('请求出错', ex)
                });
            }
        })
    }
    loadOptionData() {
        let options = []
        controls.map(c => {
            if (c.fetch) {
                let f = c.fetch;
                if (c.type === 'cascader-select') {
                    f.isCascader = true;
                }
                if (c.type !== 'search') {
                    options.push(f);
                }
            }
        })
        if (daoName && options.length > 0) {
            this.props.dispatch({ type: `${daoName}/fetchOptions`, payload: { options } });
        }
    }
    showModelHandler(isAdd) {
        let key = null
        if (!isAdd) {
            const len = this.props.selectedRowKeys.length;
            if (len === 0) {
                message.info('请选择要修改的认定关系！', 5);
                return;
            }
            key = this.props.selectedRowKeys[len - 1]
        }
        this.props.dispatch({
            type: `${daoName}/openEdit`,
            payload: { key }
        });
    }
    /**
  * 导入
  * 下载导入模板
  */
    //===============================================
    showImportHandler() {
        this.props.dispatch({
            type: `${daoName}_DataImport/setDisplay`,
            payload: { display: true },
        });
    };
    DownTmportHandler() {
        let columnHeaders = []
        columns.map((c) => {
            const name = c.dataIndex ? c.dataIndex : c.key
            if (!name || name == "emnm1") {
                return;
            }
            if (!name || name == "emnm2") {
                return;
            }
            if (!name || name == "emnm3") {
                return;
            }
            if (!name || name == "emnm4") {
                return;
            }
            if (!name || name == "emnm5") {
                return;
            }
            if (!name || name == "emnm6") {
                return;
            }
            if (!name || name == "stepName") {
                return;
            }
            let header = {
                Name: name,
                Caption: c.title,
                Width: c.width
            }
            columnHeaders.push(header)
        })
        let form = document.createElement('form');//定义一个form表单
        let whereItems = [];
        whereItems.push({
            FieldName: "ID",
            Operator: "=",
            FieldValues: "0"
        })
        const whereCauses = []
        whereCauses.push({
            WhereItems: whereItems,
            RelationSign: "AND"
        })
        const orderItems = []
        form.style = "display:none";
        form.target = "_blank";
        form.method = "post";
        form.action = `/api/ExportXlsx/${daoName}`;
        let input1 = document.createElement("input");
        input1.type = "hidden";
        input1.name = "WhereCauses";
        input1.value = JSON.stringify(whereCauses);
        let input2 = document.createElement("input");
        input2.type = "hidden";
        input2.name = "OrderItems";
        input2.value = JSON.stringify(orderItems)
        let input3 = document.createElement("input");
        input3.type = "hidden";
        input3.name = "ColumnHeaders";
        input3.value = JSON.stringify(columnHeaders);
        let input4 = document.createElement("input");
        input4.type = "hidden";
        input4.name = "PermID";
        input4.value = "" + this.props.permID;
        let input5 = document.createElement("input");
        input5.type = "hidden";
        input5.name = "UserID";
        input5.value = "" + this.props.userID;
        document.body.appendChild(form);//将表单放置在web中
        form.appendChild(input1);
        form.appendChild(input2);
        form.appendChild(input3);
        form.appendChild(input4);
        form.appendChild(input5);
        form.submit();
        document.body.removeChild(form)
    };
    //===============================================
    deleteHandler() {
        const keys = this.props.selectedRowKeys;
        const len = keys.length;
        if (len === 0) {
            message.info('请选择要删除的认定关系！', 5);
            return;
        }
        Modal.confirm({
            title: '提示',
            content: `你确认要删除选中的${len}条认定关系吗？`,
            okText: '删除',
            cancelText: '取消',
            onOk: () => {
                this.props.dispatch({
                    type: `${daoName}/remove`,
                    payload: { daoName, keys },
                });
            }
        });
    }
    edidOkHandler() {
        const form = this.refs.diviForm.getForm()
        form.validateFields((err, values) => {
          if (!err) {
            let t = `${daoName}/create`
            const { keyName, record } = this.props;
            let msg = "数据添加成功！"
            if (record[keyName]) {
              values[keyName] = record[keyName];
              t = `${daoName}/patch`
              msg = "数据修改成功！"
            }
            controls.map((c, i) => {
              if (c.type === 'cascader-select') {
                let vs = values[c.name];
                if (vs.length > 0) {
                  values[c.name] = vs[vs.length - 1];
                } else {
                  values[c.name] = null;
                }
              }
              if (c.dataType === "number") {
                values[c.name] = Number(values[c.name])
              } else if (c.dataType === "date" || c.dataType === "datetime") {
                values[c.name] = !values[c.name] ? null : new Date(values[c.name])
              } else {
                values[c.name] = values[c.name] === undefined ? null : values[c.name]
              }
              if (c.multiple || c.type === 'checkbox-group') {
                values[c.name] = values[c.name].join(',');
              }
            })
             values.UID = this.props.userID
            this.state.dataChange = true;
            this.props.dispatch({
              type: t,
              payload: { daoName, values },
            })
          }
        });
      };

      hideEditHandler() {
        const form = this.refs.diviForm.getForm();
        form.resetFields();
        if (this.state.dataChange) {
          this.props.dispatch({
            type: `${daoName}/reload`,
            payload: { daoName },
          });
          this.state.dataChange = false;
        }
        this.props.dispatch({
          type: `${daoName}/hideEdit`
        });
      };

 


    
    //延时一秒 设置isClick为false
    enableButton() {
        const that = this
        setTimeout(function () {
            that.setState({ isClick: false })
        }, 1000);
    }
  
    batchSubmitHandler(bType) {
        if (this.state.isClick) {
            return
        }
        this.setState({ isClick: true })
        const keys = this.props.selectedRowKeys;
        const len = keys.length;
        if (len === 0) {
            message.info('请选择要提交的认定关系！', 5);
            this.enableButton()
            return;
        }
        const list = this.props.list
        let runIDs = []
        let isOK = true
        list.map(row => {
            if (keys.find(key => row.ID === key)) {
                if (!row.FRID) {
                    isOK = false
                }
                runIDs.push(row.FRID)
            }
        })
        if (!isOK) {
            message.info('要提交的认定关系存在校验错误，请修改！', 5);
            this.enableButton()
            return;
        }
        bType = "agree"
        let ishld = 0
        if (list[0].step === 4) {
            Modal.confirm({
                title: '提示',
                content: `请确认是否是亿元客户且需要行领导进行审批？`,
                okText: '需要',
                cancelText: '不需要',
                onOk: () => {
                    ishld = 1
                    this.props.dispatch({
                        type: `${daoName}/flowBatchSubmit`,
                        payload: { runIDs, userID: this.props.userID, desc: "", bType, ishld },
                    });
                    this.cancelHandler()
                    this.enableButton()
                },
                onCancel: () => {
                    ishld = 0
                    this.props.dispatch({
                        type: `${daoName}/flowBatchSubmit`,
                        payload: { runIDs, userID: this.props.userID, desc: "", bType, ishld },
                    });
                    this.cancelHandler()
                    this.enableButton()
                }
            });
        } else {
            ishld = 0
            this.props.dispatch({
                type: `${daoName}/flowBatchSubmit`,
                payload: { runIDs, userID: this.props.userID, desc: "", bType, ishld },
            });
            this.cancelHandler()
            this.enableButton()
        }
    }

    submitHandler(bType) {
        const { runID } = this.props.flowRunInfo
        bType = "agree"
        this.props.dispatch({
            type: `${daoName}/flowSubmit`,
            payload: { runID, userID: this.props.userID, desc: "", bType },
        });
        this.cancelHandler()
    }
    setExecutorHandler() {
        const { runID, currStep } = this.props.flowRunInfo
        const { checkVals } = this.state
        if (checkVals === "") {
            message.info("请您选择办理人！", 5)
        }
        this.props.dispatch({
            type: `${daoName}/setFolwExecutor`,
            payload: { runID, stepID: currStep, userIDstr: checkVals },
        });
    };
    sendBackHandler(bType) {
        const { runID, currStep } = this.props.flowRunInfo
        const { text } = this.state
        if (text === "") {
            message.info("请您填写退回意见！", 5)
            return
        }
        let bStep = 1
        let ts = "你确认要退回申请人吗"
        if (bType === "backPrev") {
            bStep = currStep - 1
            ts = "你确认要退回上一步吗"
        }
        Modal.confirm({
            title: '提示',
            content: ts,
            okText: '退回',
            cancelText: '取消',
            onOk: () => {
                this.props.dispatch({
                    type: `${daoName}/flowSendBack`,
                    payload: { runID, userID: this.props.userID, backStepID: bStep, desc: text },
                });
            }
        });
    }
    abortHandler() {
        if (this.state.isClick) {
            return
        }
        this.setState({ isClick: true })
        const keys = this.props.selectedRowKeys;
        const len = keys.length;
        if (len === 0) {
            message.info('请选择要中止的认定关系！', 5);
            this.enableButton()
            return;
        }
        const list = this.props.list
        let runIDs = []
        let isOK = true
        list.map(row => {
            if (keys.find(key => row.ID === key)) {
                if (!row.FRID) {
                    isOK = false
                }
                runIDs.push(row.FRID)
            }
        })
        Modal.confirm({
            title: '提示',
            content: `你确认要中止此流程吗？`,
            okText: '中止',
            cancelText: '取消',
            onOk: () => {
                this.props.dispatch({
                    type: `${daoName}/flowAbort`,
                    payload: { runIDs },
                });
            }
        });
        this.enableButton()
    }
    cancelHandler() {
        this.props.dispatch({
            type: `${daoName}/setFrid`,
            payload: { frid: 0 },
        });
    }
    doFlowHandler() {
        const { selectedRowKeys } = this.props
        if (selectedRowKeys.length === 0) {
            message.info("请选择要办理流程！", 5)
            return
        }
        const frid = selectedRowKeys[0]
        this.props.dispatch({
            type: `${daoName}/fetchFlowRunInfo`,
            payload: { runID: frid },
        });
    }
    rangeChangeHandler(e) {
        this.state.range = e.key
        this.loadData()
    }
    showStepHandler() {
        const len = this.props.selectedRowKeys.length;
        if (len === 0) {
            message.info('请选择要修改的认定关系！', 5);
            return;
        }
        const key = this.props.selectedRowKeys[len - 1]
        const list = this.props.list
        const index = list.findIndex(v => v.ID === key)
        const runID = list[index].FRID
        if (!runID) {
            message.info('选择的认定关系存在校验错误，请修改！', 5);
            return;
        }
        this.props.dispatch({
            type: `${daoName}/fetchFlowRunInfo`,
            payload: { runID }
        });
    }
    hideStepHandler() {
        this.props.dispatch({
            type: `${daoName}/hideStep`,
            payload: {}
        });
    }
    onSelectChange(newList, delKeys) {
        let canEdit = false
        const oldKeys = this.props.selectedRowKeys;
        let keys = []
        oldKeys.forEach(key => {
            let isFind = false
            if (delKeys.find(key2 => key2 === key)) {
                isFind = true
            }
            if (!isFind) {
                keys.push(key)
            }
        })
        newList.forEach(row => {
            keys.push(row.ID)
        });
        const len = keys.length;
        if (len > 0) {
            const list = this.props.list
            let isOK = true
            list.map(row => {
                if (keys.find(key => row.ID === key)) {
                    if (row.step !== 1) {
                        isOK = false
                    }
                }
            })
            if (isOK) {
                canEdit = true
            }
        }
        this.setState({ canEdit })
    }
    acnoChangeHandler(e) {
        const acno = e.target.value
        this.state.acno = acno
    }
    banoChangeHandler(e) {
        const bano = e.target.value
        const acno = this.state.acno
        if (acno && acno != "" && bano && bano != "") {
            this.props.dispatch({
                type: `${daoName}/fetchAcno`,
                payload: { acno, bano }
            });
        }
    }
    renderStep() {
        const { flowRunInfo } = this.props
        const steps = flowRunInfo.stepList.map(s => {
            let desc = "未开始"
            let iszz=false
            if (flowRunInfo.state === '2' && flowRunInfo.currStep === s.id) {
                desc = "已中止"
                iszz=true

            } else if (s.state === '1') {
                desc = "办理中..."
            } else if (s.state === '2') {
                desc = "已办理"
            }
            const content = s.executors.map(e => <div key={e.id} ><span>{`${e.name}(${e.department})：`}</span><br/>
             <span style={{ color: e.desc != "待办..." && e.desc !== "未办" ? desc === "已中止" || e.desc === "管理员强制提交" ? "#FA541C" : "#0D993A" : "gray" }}>{iszz===false ? e.desc:"中止"}</span></div>)

            {/* <span style={{ color: e.desc != "在办..." ? desc === "已中止" ? "#FA541C" : "#0D993A" : "gray" }}>{e.desc}</span></div>) */}
            const descTag = <div style={{ maxHeight: "200px", overflow: "auto" }}>{content}</div>
            return <Step key={s.id} title={s.name + `【` + desc + `】`} description={descTag} />
        })
        let status = "process"
        if (flowRunInfo.state === "1") {
            status = "finish"
        } else if (flowRunInfo.state === "2") {
            status = "error"
        } else {
            const step = flowRunInfo.stepList[flowRunInfo.currStep - 1]
            if (step.appointer && step.appointer.length > 0 && step.executors.length == 0) {
                status = "wait"
            }
        }
        const current = flowRunInfo.currStep - 1
        return <Steps direction="vertical" current={current} status={status}>{steps}</Steps>
    }
    renderList() {
        let { permID, showStep, showEdit, record, userID, userName, selectedRowKeys } = this.props
        const { range, canEdit, isClick } = this.state
        const attachP = {
            UID: '' + userID
        }
        record.EMNO1 = userName
        // const menu = <Menu onClick={this.rangeChangeHandler.bind(this)}>
            {/* <Menu.Item key="doing">在办</Menu.Item>
            <Menu.Item key="done">已办</Menu.Item>
            <Menu.Item key="all">全部</Menu.Item> */}
        // </Menu>
        // const title = ""
        const butts = <ButtonGroup style={{ zIndex: 0 }}>
            {/* <Dropdown overlay={menu} trigger={['click']}> */}
                {/* <Button type="ghost" style={{ margin: 5 }}> */}
                    {/* {range === "doing" ? "在办" : range === "done" ? "已办" : "全部"}<Icon type="down" /> */}
                {/* </Button> */}
            {/* </Dropdown> */}
            {/* {range === "doing" ? <Button onClick={this.showModelHandler.bind(this, true)}>新增</Button> : null}  */}
            {/* {range === "doing" && canEdit ? <Button onClick={this.showModelHandler.bind(this, false)}>修改</Button> : null} */}
            {/* {range === "doing" && canEdit ? <Button onClick={this.deleteHandler.bind(this)}>删除</Button> : null} */}
            {/* {range === "doing" ? <Tooltip placement="left" title={title}> */}
            {/* <Button onClick={this.showImportHandler.bind(this)}>导入</Button>  */}
            {/* </Tooltip> : null} */}
            {/* {range === "doing" ? <Button onClick={this.DownTmportHandler.bind(this)}>下载导入模板</Button> : null} */}
            <Button onClick={this.showStepHandler.bind(this)}>查看进度</Button>
            {/* {range === "doing" ? <Button onClick={this.batchSubmitHandler.bind(this)} disabled={isClick}>提交</Button> : null} */}
             {/* {range === "doing" && selectedRowKeys.length > 0 && !canEdit ? <Button onClick={this.abortHandler.bind(this)} disabled={isClick}>中止</Button> : null} */}
        </ButtonGroup>
        return (
            <div className={styles.normal} style={{ background: '#fff', marginTop: -16, padding: '5px 5px' }}>
                <div>
                    <div className={styles.create}>
                        {butts}
                    </div>
                    <Modal title="流程运行" width={700} visible={showEdit} onOk={this.edidOkHandler.bind(this)} onCancel={this.hideEditHandler.bind(this)} maskClosable={false}
                        footer={[
                            <Button key="close" type="ghost" onClick={this.hideEditHandler.bind(this)}>关闭</Button>,
                            <Button key="submit" type="primary" onClick={this.edidOkHandler.bind(this)}>保存</Button>
                        ]}
                    >
                        <EditFrom ref="diviForm" daoName={daoName} controls={controls} record={record} />
                    </Modal>
                    <DataTable ref="diviTable" daoName={daoName} columns={columns} controls={controls} permID={permID} onSelectChange={this.onSelectChange.bind(this)} />
                    {showStep ? <Modal title={this.state.stepTitle} width={400} visible={showStep} onCancel={this.hideStepHandler.bind(this)}
                        footer={null}
                    >
                        {this.renderStep()}
                    </Modal> : null}
                </div>
            </div>
        )
    }
    render() {
        return this.renderList()
    }
}

function mapStateToProps(state) {
    const { showEdit, showStep, record, list, selectedRowKeys, keyName, flowRunInfo, frid } = state[daoName];
    const { record: record2, list: list2, selectedRowKeys: selectedRowKeys2 } = state["CompAccoFlow"];
    const { userID, orgID, pOrgID, popedomTypes, userName, UserNo, RDDate } = state.menus;
    return {
        loading: state.loading.models[daoName],
        userID,
        orgID,
        pOrgID, userName, UserNo,
        popedomTypes,
        list,
        list2, RDDate,
        showEdit,
        showStep,
        selectedRowKeys,
        selectedRowKeys2,
        keyName,
        record,
        record2,
        flowRunInfo,
        frid,
    }
}
LCYXCollect = connect(mapStateToProps)(LCYXCollect)
export default LCYXCollect;
let render = (props) => React.createElement(LCYXCollect, props);
let f = new Factory()
f.set("LCYXCollect", render)
